package org.wu.framework.saas.share.platform.filter;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.filter.OncePerRequestFilter;
import org.wu.framework.core.utils.ObjectUtils;
import org.wu.framework.saas.share.platform.prop.SaasShareProp;
import org.wu.framework.saas.share.platform.toolkit.SaasShareContextHolder;

import java.io.IOException;


@Slf4j
@Configuration
public class SaasShareDataBaseHandlerFilter extends OncePerRequestFilter {

    private final SaasShareProp saasShareProp;

    private AntPathMatcher matcher = new AntPathMatcher();

    public SaasShareDataBaseHandlerFilter(SaasShareProp saasShareProp) {
        this.saasShareProp = saasShareProp;
    }

    /**
     * Same contract as for {@code doFilter}, but guaranteed to be
     * just invoked once per request within a single request thread.
     * See {@link #shouldNotFilterAsyncDispatch()} for details.
     * <p>Provides HttpServletRequest and HttpServletResponse arguments instead of the
     * default ServletRequest and ServletResponse ones.
     *
     * @param request
     * @param response
     * @param filterChain
     */
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {


        String requestURI = request.getRequestURI();
        log.debug("请求地址：{}", requestURI);
        // 这些api忽略 数据隔离限制
        if (saasShareProp.getUnCheckApiPath().stream().noneMatch(unCheck -> matcher.match(unCheck, requestURI))) {
            String requestHeaderShareKey = saasShareProp.getRequestHeaderShareKey();
            // 根据用户ID切换schema
            String shareColumnValue = request.getHeader(requestHeaderShareKey);

            if (!ObjectUtils.isEmpty(shareColumnValue)) {
                SaasShareContextHolder.push(shareColumnValue);
            }else {
                log.error("请求地址{}中不包含数据隔离字段:{},{}。请检查....", requestURI,requestHeaderShareKey,shareColumnValue);
            }
        }
        // 拦截器处理
        filterChain.doFilter(request, response);

        // 清除 Lazy上下文的数据源
        SaasShareContextHolder.clear();
    }

}
